import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView'
import AdminInterface from '../views/AdminInterface'
import User from '../views/User'
import Interviewee from '../views/Interviewee.vue'
import Interviewer from '../views/Interviewer'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: LoginView
  }, {
    path: '/Interviewee',
    name: 'Interviewee',
    component: Interviewee
  }, {
    path: '/Interviewer',
    name: 'Interviewer',
    component: Interviewer
  }, {
    path: '/User',
    name: 'User',
    component: User
  }, {
    path: '/login',
    name: 'login',
    component: LoginView
  }, {
    path: '/admin',
    name: 'admin',
    component: AdminInterface
  }

]

const router = new VueRouter({
  routes
})

const isAuthenticated = async () => {
  return await fetch('api/me')
    .then((res) => res.json())
    .then((data) => {
      return data.status !== 'ERROR'
    })
}

router.beforeEach(async (to, from, next) => {
  const bool = await isAuthenticated()
  if (to.name !== 'login' && to.name !== 'home' && !bool) {
    window.alert('未登录！')
    next('/login')
  } else {
    next()
  }
})

export default router
